package com.kly.cashmall.module.home.home_tab.tab_container;

import android.annotation.SuppressLint;
import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.kly.cashmall.module.home.home_tab.tab_data.TabBox;
import com.kly.cashmall.module.home.home_tab.tab_view.TabItem;
import com.kly.cashmall.utils.function.BundleHelper;
import com.kly.cashmall.utils.ListIndexFind;
import com.kly.cashmall.utils.ReflectUtil;
import com.kly.cashmall.utils.data.TextUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

public class TabController {

  private FragmentActivity fragmentActivity;
  private TabContainerView managerView;

  private List<TabBox> tabBoxes;
  private TabContainerView.OnItemClickListener onItemClickListener;
  private Fragment currentFragment;
  private int currentPos;

  public TabController(FragmentActivity fragmentActivity, TabContainerView tabManagerView) {
    this.fragmentActivity = fragmentActivity;
    this.managerView = tabManagerView;
    this.managerView.setItemClickListener((pos, view) -> {
      if (onItemClickListener != null) {
        return onItemClickListener.onItemClick(pos, view);
      }
      return true;
    });
    initList();
//    fixHuaWeiBug();
  }

  private void initList() {
    tabBoxes = new ArrayList<>();
  }

  /**
   * 华为设置权限后会重新执行onCreate ,但是FragmentManager的页面不销毁，这边直接先全部销毁
   */
  private void fixHuaWeiBug() {
    FragmentManager fm = fragmentActivity.getSupportFragmentManager();
    FragmentTransaction ft = fm.beginTransaction();

    //当前所有fragment
    @SuppressLint("RestrictedApi") List<Fragment> fragments = fm.getFragments();
    if (fragments != null && fragments.size() > 0) {
      for (Fragment f : fragments) {
        if (f != null) {
          ft.remove(f);
        }
      }
      ft.commitAllowingStateLoss();
    }
  }

  public Fragment getCurrentFragment() {
    return currentFragment;
  }

  public int getCurrentPos() {
    return currentPos;
  }

  public String getCurrentTag() {
    if (currentPos >= 0 && currentPos < tabBoxes.size()) {
      return tabBoxes.get(currentPos).tag;
    }
    return "";
  }

  public void addTabs(List<TabItem> tabItems) {
    if (tabItems != null) {
      for (TabItem item : tabItems) {
        addTab(item);
      }
    }
  }

  /**
   * 向TabManagerView添加TabItem
   */
  public void addTab(TabItem tabItem) {

    Fragment fragment = tabItem.getFragment();
    if (fragment != null) {
      tabBoxes.add(new TabBox(tabItem.getTag(), fragment, tabItem));
      managerView.addTabChild(tabItem.getTabView());
    }
  }

  /**
   * 通过tag找到TabItem的序号
   */
  public int findIndexByTag(final String tag) {
    if (TextUtil.isEmpty(tag)) {
      return -1;
    }
    return ListIndexFind.findIndex(tabBoxes, tag,
            new ListIndexFind.ObjectCompare<TabBox, String>() {
              @Override
              public boolean compare(TabBox tabBox, String s) {
                return String.valueOf(s).equals(tabBox.tag);
              }
            });
  }

  public TabItem getTabItem(String tagName) {
    int index = findIndexByTag(tagName);
    if (index >= 0) {
      return tabBoxes.get(index).tabItem;
    }
    return null;
  }

  public Fragment findFragmentByTag(String tag) {
    return fragmentActivity.getSupportFragmentManager().findFragmentByTag(tag);
  }

  public String getTag(int index) {
    return (index >= 0 && index < tabBoxes.size()) ? tabBoxes.get(index).tag : "";
  }

  public Fragment getFragment(int index) {
    return (index >= 0 && index < tabBoxes.size()) ? tabBoxes.get(index).fragment : null;
  }

  public TabItem getTabItem(int index) {
    return (index >= 0 && index < tabBoxes.size()) ? tabBoxes.get(index).tabItem : null;
  }

  /**
   * 通过tag选择fragment（tag默认情况下就是fragment的SimpleName）
   */
  public void setSelectionByTag(String tag, Bundle extra) {
    setSelection(findIndexByTag(tag), extra);
  }

  /**
   * 选择显示的TabItem,传参
   */
  public void setSelection(int pos, Bundle extra) {
    if (managerView.getSize() == 0) {
      return;
    }
    if (pos < 0 || pos >= managerView.getSize()) {
      pos = 0;
    }

    FragmentManager fm = fragmentActivity.getSupportFragmentManager();

    boolean hasAdded = false;
    Fragment fragment = fm.findFragmentByTag(getTag(pos));
    if (fragment == null) {
      fragment = getFragment(pos);
    } else {
      hasAdded = true;
    }

    if (fragment == null) {
      return;
    }

    currentPos = pos;
    currentFragment = fragment;

    FragmentTransaction ft = fm.beginTransaction();

    //影藏当前所有fragment
    @SuppressLint("RestrictedApi") List<Fragment> fragments = fm.getFragments();
    if (fragments != null && fragments.size() > 0) {
      for (Fragment f : fragments) {
        if (f != null && f != fragment) {
          ft.hide(f);
        }
      }
    }

//    if (!hasAdded && !fragment.isAdded()) {
      if (extra != null) {
        Object obj = ReflectUtil.getField(Fragment.class, fragment, "mIndex");
        int index = -1;
        if (obj != null) {
          index = (int) obj;
        }
        if (index < 0) {
          if (fragment.getArguments() != null) {
            fragment.setArguments(
                    BundleHelper.create(new Bundle(fragment.getArguments())).putAll(extra).get());
          } else {
            fragment.setArguments(extra);
          }
        }
      }
//    } else {
//      if (fragment instanceof ArgumentsUpdateControl) {
//        ((ArgumentsUpdateControl) fragment).updateArguments(extra);
//      }
//    }

    if (hasAdded || fragment.isAdded()) {
      ft.show(fragment).commitAllowingStateLoss();
    } else {
      ft.add(managerView.getFragmentContainerId(), fragment, getTag(pos)).commitAllowingStateLoss();
    }
    managerView.setSelectedItem(pos);
    if (getTabItem(pos) != null) {
      getTabItem(pos).setRedDot(false);
    }
  }

  public void setOnItemClickListener(TabContainerView.OnItemClickListener onItemClickListener) {
    this.onItemClickListener = onItemClickListener;
  }

  /**
   * 清除所有的数据
   */
  public void clearAllTab() {
    managerView.removeTabContainer();
    tabBoxes.clear();
    FragmentManager fm = fragmentActivity.getSupportFragmentManager();
    //影藏当前所有fragment
    @SuppressLint("RestrictedApi") List<Fragment> fragments = fm.getFragments();
    int size = fragments != null ? fragments.size() : 0;

    if (size == 0) {
      return;
    }

    FragmentTransaction ft = fm.beginTransaction();
    for (Fragment f : fragments) {
      if (f != null && f.isAdded()) {
        ft.remove(f);
      }
    }
    ft.commitAllowingStateLoss();
  }


  /**
   * tag匹配规则
   */
  public static boolean tagMatchRule(String regex, String action) {
    if (TextUtil.isEmpty(regex)) {
      return false;
    }
    return regex.equals(action) || Pattern.compile(regex).matcher(action).find();
  }
}